package com.yifeng.repo.base.utils.servlet;

import com.google.common.base.Strings;
import com.yifeng.repo.base.utils.common.BaseUtil;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by daibing on 2023/8/25.
 */
public abstract class AbstractFilter implements Filter {
    protected final String PATH_SPLIT_REGX = "[;, ，；]";
    protected AntPathMatcher matcher = new AntPathMatcher();
    private final String[] excludePath;

    public AbstractFilter(String excludeUri) {
        this.excludePath = getParamToArray(excludeUri);
    }

    public AbstractFilter(String[] excludePath) {
        this.excludePath = Arrays.stream(excludePath).map(String::toLowerCase).toArray(value -> new String[excludePath.length]);
    }

    private String[] getParamToArray(String conf) {
        if (Strings.isNullOrEmpty(conf)) {
            return new String[0];
        } else {
            List<String> list = new ArrayList<>();
            String[] bs = conf.trim().split(PATH_SPLIT_REGX);
            for (String b : bs) {
                if (!Strings.isNullOrEmpty(b)) {
                    String path = b.trim().toLowerCase();
                    list.add(path.startsWith("/") ? path : "/" + path);
                }
            }
            return list.toArray(new String[0]);
        }
    }

    protected String getInitParameter(FilterConfig fc, String servletParamName, String contextParamName) {
        String param = fc.getInitParameter(servletParamName);
        if (BaseUtil.isBlank(param)) {
            param = fc.getServletContext().getInitParameter(contextParamName);
        }
        return BaseUtil.isBlank(param) ? null : param.trim();
    }

    protected boolean isExcludeUri(String uri) {
        for (String exclude : excludePath) {
            if (this.isMatch(exclude, uri)) {
                return true;
            }
        }
        return false;
    }

    protected boolean isMatch(String pattern, String uri) {
        if (pattern.contains("*") || pattern.contains("?")) {
            return matcher.match(pattern, uri);
        }
        return uri.equalsIgnoreCase(pattern);
    }
}
